package listener;

import javax.servlet.*;
import javax.servlet.http.*;
import javax.servlet.annotation.*;

@WebListener
public class UserCountListener implements HttpSessionListener{


    @Override
    public void sessionCreated(HttpSessionEvent se) {
        /* Session is created. */

        ServletContext ctx = se.getSession().getServletContext();
        Integer count = (Integer) ctx.getAttribute("OnlineCount");
        HttpSession session = se.getSession();

        if (count == null) {
            count = 1;
        } else {
            count = count + 1;
        }
        ctx.setAttribute("OnlineCount", count);

    }

    @Override
    public void sessionDestroyed(HttpSessionEvent se) {
        /* Session is destroyed. */
        ServletContext ctx = se.getSession().getServletContext();
        Integer count = (Integer) ctx.getAttribute("OnlineCount");
        HttpSession session = se.getSession();

        if (count == null) {
            count = 0;
        } else {
            count = count - 1;
        }
        ctx.setAttribute("OnlineCount", count);

    }





}
